home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1998 November: Tool Chest / Dev.CD Nov 98 TC.toast / Sample Code / Overview / TESample / TESample.p < prev    next >
Encoding:
Text File  |  1994-11-18  |  51.3 KB  |  1,594 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    TESample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                06/92
  20. #
  21. #    Components:
  22. #                TESample.p            June 1, 1989
  23. #                TESample.c            June 1, 1989
  24. #                TESampleInit.c        June 4, 1992
  25. #                TESampleGlue.a        June 1, 1989
  26. #                TESample.r            June 1, 1989
  27. #                TESample.h            June 1, 1989
  28. #                PTESample.make        June 1, 1989
  29. #                CTESample.make        June 1, 1989
  30. #                TCTESample.π        June 4, 1992
  31. #                TCTESample.π.rsrc    June 4, 1992
  32. #                TCTESampleGlue.c    June 4, 1992
  33. #
  34. #    TESample is an example application that demonstrates how 
  35. #    to initialize the commonly used toolbox managers, operate 
  36. #    successfully under MultiFinder, handle desk accessories and 
  37. #    create, grow, and zoom windows. The fundamental TextEdit 
  38. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  39. #    also shows how to create and maintain scrollbar controls.
  40. #
  41. #    It does not by any means demonstrate all the techniques you 
  42. #    need for a large application. In particular, Sample does not 
  43. #    cover exception handling, multiple windows/documents, 
  44. #    sophisticated memory management, printing, or undo. All of 
  45. #    these are vital parts of a normal full-sized application.
  46. #
  47. #    This application is an example of the form of a Macintosh 
  48. #    application; it is NOT a template. It is NOT intended to be 
  49. #    used as a foundation for the next world-class, best-selling, 
  50. #    600K application. A stick figure drawing of the human body may 
  51. #    be a good example of the form for a painting, but that does not 
  52. #    mean it should be used as the basis for the next Mona Lisa.
  53. #
  54. #    We recommend that you review this program or Sample before 
  55. #    beginning a new application. Sample is a simple app. which doesn’t 
  56. #    use TextEdit or the Control Manager.
  57. #
  58. ------------------------------------------------------------------------------}
  59.  
  60.  
  61. PROGRAM TESample;
  62.  
  63.  
  64. {Segmentation strategy:
  65.  
  66.  This program consists of three segments. Main contains most of the code,
  67.  including the MPW libraries, and the main program. Initialize contains
  68.  code that is only used once, during startup, and can be unloaded after the
  69.  program starts. %A5Init is automatically created by the Linker to initialize
  70.  globals for the MPW libraries and is unloaded right away.}
  71.  
  72.  
  73. {SetPort strategy:
  74.  
  75.  Toolbox routines do not change the current port. In spite of this, in this
  76.  program we use a strategy of calling SetPort whenever we want to draw or
  77.  make calls which depend on the current port. This makes us less vulnerable
  78.  to bugs in other software which might alter the current port (such as the
  79.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  80.  Hopefully, this also makes the routines from this program more self-contained,
  81.  since they don't depend on the current port setting.}
  82.  
  83.  
  84. {Clipboard strategy:
  85.  
  86.  This program does not maintain a private scrap. Whenever a cut, copy, or paste
  87.  occurs, we import/export from the public scrap to TextEdit's scrap right away,
  88.  using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  89.  the import/export would be in the activate/deactivate event and suspend/resume
  90.  event routines.}
  91.  
  92. {$D+}
  93.  
  94. USES
  95.     Types, QuickDraw, Events, Controls, Windows, TextEdit, Dialogs, Fonts, Lists,
  96.     Menus, Resources, Scrap, ToolUtils, 
  97.     OSUtils, Files, Devices, DeskBus, DiskInit, Disks, Errors, Memory, Retrace,
  98.     SegLoad, Serial,
  99.     ShutDown, Slots, Sound, Start, Timer, Packages, Traps;
  100.  
  101.  
  102. CONST
  103.     {MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  104.      These constants are from that file.}
  105.     {1.02 - Uses Traps.p to obtain trap numbers.}
  106.  
  107.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  108.     {kTextMargin is the number of pixels we leave blank at the edge of the window.}
  109.     kTextMargin                = 2;
  110.  
  111.     {kMaxOpenDocuments is used to determine whether a new document can be opened
  112.      or created. We keep track of the number of open documents, and disable the
  113.      menu items that create a new document when the maximum is reached. If the
  114.      number of documents falls below the maximum, the items are enabled again.}
  115.     kMaxOpenDocuments        = 1;
  116.     
  117.     {kMaxDocWidth is an arbitrary number used to specify the width of the TERec's
  118.     destination rectangle so that word wrap and horizontal scrolling can be
  119.     demonstrated.}
  120.     kMaxDocWidth            = 576;
  121.     
  122.     {kMinDocDim is used to limit the minimum dimension of a window when GrowWindow
  123.     is called.}
  124.     kMinDocDim                = 64;
  125.     
  126.     {kControlInvisible is used to 'turn off' controls (i.e., cause the control not
  127.     to be redrawn as a result of some Control Manager call such as SetControlValue)
  128.     by being put into the contrlVis field of the record. kControlVisible is used
  129.     the same way to 'turn on' the control.}
  130.     kControlInvisible        = 0;
  131.     kControlVisible            = $FF;
  132.     
  133.     {kScrollBarAdjust and kScrollBarWidth are used in calculating
  134.     values for control positioning and sizing.}
  135.     kScrollbarWidth            = 16;
  136.     kScrollbarAdjust        = kScrollbarWidth - 1;
  137.     
  138.     {kScrollTweek compensates for off-by-one requirements of the scrollbars
  139.      to have borders coincide with the growbox.}
  140.     kScrollTweek            = 2;
  141.     
  142.     {kCrChar is used to match with a carriage return when calculating the
  143.     number of lines in the TextEdit record. kDelChar is used to check for
  144.     delete in keyDowns.}
  145.     kCRChar                    = 13;
  146.     kDelChar                = 8;
  147.     
  148.     {kButtonScroll is how many pixels to scroll horizontally when the button part
  149.     of the horizontal scrollbar is pressed.}
  150.     kButtonScroll            = 4;
  151.     
  152.     {kMaxTELength is an arbitrary number used to limit the length of text in the TERec
  153.     so that various errors won't occur from too many characters in the text.}
  154.     kMaxTELength            = 32000;
  155.  
  156.     {kSysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  157.      SysEnvRec we understand.}
  158.     kSysEnvironsVersion        = 1;
  159.  
  160.     {kOSEvent is the event number of the suspend/resume and mouse-moved events sent
  161.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  162.      high byte of the message sent to determine which kind it is. To differentiate
  163.      suspend and resume events we check the resumeMask bit.}
  164.     kOSEvent                = app4Evt;    {event used by MultiFinder}
  165.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  166.     kResumeMask                = 1;        {bit of message field for resume vs. suspend}
  167.     kMouseMovedMessage        = $FA;        {high byte of mouse-moved event message}
  168.     kNoEvents                = 0;        {no events mask}
  169.  
  170.     {1.01 - kMinHeap - This is the minimum result from the following
  171.      equation:
  172.             
  173.             ORD(GetApplLimit) - ORD(ApplicationZone)
  174.             
  175.      for the application to run. It will insure that enough memory will
  176.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  177.      application, and still give the application some 'breathing room'.
  178.      To derive this number, we ran under a MultiFinder partition that was
  179.      our requested minimum size, as given in the 'SIZE' resource.}
  180.      
  181.     kMinHeap    = 29 * 1024;
  182.     
  183.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  184.      at initialization time, for the application to run. This number acts
  185.      as a double-check to insure that there really is enough memory for the
  186.      application to run, including what has been taken up already by
  187.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  188.      
  189.     kMinSpace    = 20 * 1024;
  190.     
  191.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  192.     kExtremeNeg        = -32768;
  193.     kExtremePos        = 32767 - 1;    {required for old region bug}
  194.     
  195.     {kTESlop provides some extra security when pre-flighting edit commands.}
  196.     kTESlop            = 1024;
  197.  
  198.     {kErrStrings is the resource ID for the error strings STR# resource.}
  199.     kErrStrings        = 128;
  200.  
  201.     {The following are indicies into STR# resources.}
  202.     eWrongMachine    = 1;
  203.     eSmallSize        = 2;
  204.     eNoMemory        = 3;
  205.     eNoSpaceCut        = 4;
  206.     eNoCut            = 5;
  207.     eNoCopy            = 6;
  208.     eExceedPaste    = 7;
  209.     eNoSpacePaste    = 8;
  210.     eNoWindow        = 9;
  211.     eExceedChar        = 10;
  212.     eNoPaste        = 11;
  213.     
  214.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  215.     rMenuBar    = 128;                    {application's menu bar}
  216.     rAboutAlert    = 128;                    {about alert}
  217.     rUserAlert    = 129;                    {user error alert}
  218.     rDocWindow    = 128;                    {application's window}
  219.     rVScroll    = 128;                    {vertical scrollbar control}
  220.     rHScroll    = 129;                    {horizontal scrollbar control}
  221.  
  222.     {The following constants are used to identify menus and their items. The menu IDs
  223.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  224.     mApple        = 128;                    {Apple menu}
  225.     iAbout        = 1;
  226.  
  227.     mFile        = 129;                    {File menu}
  228.     iNew        = 1;
  229.     iClose        = 4;
  230.     iQuit        = 12;
  231.  
  232.     mEdit        = 130;                    {Edit menu}
  233.     iUndo        = 1;
  234.     iCut        = 3;
  235.     iCopy        = 4;
  236.     iPaste        = 5;
  237.     iClear        = 6;
  238.  
  239.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  240.     kDITop        = $0050;
  241.     kDILeft        = $0070;
  242.  
  243.  
  244. TYPE
  245.     {A DocumentRecord contains the WindowRecord for one of our document windows,
  246.      as well as the TEHandle for the text we are editing. We have added fields to
  247.      hold the ControlHandles to the vertical and horizontal scrollbars and to hold
  248.      the address of the default clickLoop that gets attached to a TERec when you call
  249.      TEAutoView. Other document fields can be added to this record as needed. For
  250.      a similar example, see how the Window Manager and Dialog Manager add fields
  251.      after the GrafPort.}
  252.     DocumentRecord    = RECORD
  253.         docWindow    : WindowRecord;
  254.         docTE        : TEHandle;
  255.         docVScroll    : ControlHandle;
  256.         docHScroll    : ControlHandle;
  257.         docClick    : TEClickLoopUPP;
  258.     END;
  259.     DocumentPeek    = ^DocumentRecord;
  260.  
  261.  
  262. VAR
  263.     {The "g" prefix is used to emphasize that a variable is global.}
  264.  
  265.     {GMac is used to hold the result of a SysEnvirons call. This makes
  266.      it convenient for any routine to check the environment. It is
  267.      global information, anyway.}
  268.     gMac                : SysEnvRec;    {set up by Initialize}
  269.  
  270.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  271.      trap is available. If it is false, we know that we must call GetNextEvent.}
  272.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  273.  
  274.     {GInBackground is maintained by our OSEvent handling routines. Any part of
  275.      the program can check it to find out if it is currently in the background.}
  276.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  277.  
  278.     {GNumDocuments is used to keep track of how many open documents there are
  279.      at any time. It is maintained by the routines that open and close documents.}
  280.     gNumDocuments        : INTEGER;        {maintained by Initialize, DoNew, and DoCloseWindow}
  281.  
  282.     
  283. {$S Initialize}
  284. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  285.  
  286. {Check to see if a given trap is implemented. This is only used by the
  287.  Initialize routine in this program, so we put it in the Initialize segment.
  288.  The recommended approach to see if a trap is implemented is to see if
  289.  the address of the trap routine is the same as the address of the
  290.  Unimplemented trap.}
  291. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  292.  if a ToolTrap is out of range of a pre-MacII ROM.}
  293.  
  294. BEGIN
  295.     IF (tType = ToolTrap) &
  296.         (gMac.machineType > envMachUnknown) &
  297.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  298.         tNumber := BAND(tNumber, $03FF);
  299.         IF tNumber > $01FF THEN                            {which means the tool traps}
  300.             tNumber := _Unimplemented;                    {only go to $01FF}
  301.     END;
  302.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  303.                         NGetTrapAddress(_Unimplemented, ToolTrap);
  304. END; {TrapAvailable}
  305.  
  306.  
  307. {$S Main}
  308. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  309.  
  310. {Check if a window belongs to a desk accessory.}
  311.  
  312. BEGIN
  313.     IF window = NIL THEN
  314.         IsDAWindow := FALSE
  315.     ELSE    {DA windows have negative windowKinds}
  316.         IsDAWindow := WindowPeek(window)^.windowKind < 0;
  317. END; {IsDAWindow}
  318.  
  319.  
  320. {$S Main}
  321. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  322.  
  323. {Check to see if a window belongs to the application. If the window pointer
  324.  passed was NIL, then it could not be an application window. WindowKinds
  325.  that are negative belong to the system and windowKinds less than userKind
  326.  are reserved by Apple except for windowKinds equal to dialogKind, which
  327.  mean it is a dialog.
  328.  1.02 - In order to reduce the chance of accidentally treating some window
  329.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  330.  is userKind. If you add different kinds of windows to Sample you'll need
  331.  to change how this all works.}
  332.  
  333. BEGIN
  334.     IF window = NIL THEN
  335.         IsAppWindow := FALSE
  336.     ELSE    {application windows have windowKinds = userKind (8)}
  337.         WITH WindowPeek(window)^ DO
  338.             IsAppWindow := (windowKind = userKind);
  339. END; {IsAppWindow}
  340.  
  341.  
  342. {$S Main}
  343. PROCEDURE AlertUser(error: INTEGER);
  344.  
  345. {Display an alert that tells the user an error occurred, then exit the program.
  346.  This routine is used as an ultimate bail-out for serious errors that prohibit
  347.  the continuation of the application. Errors that do not require the termination
  348.  of the application should be handled in a different manner. Error checking and
  349.  reporting has a place even in the simplest application. The error number is used
  350.  to index an 'STR#' resource so that a relevant message can be displayed.}
  351.  
  352. VAR
  353.     itemHit    : INTEGER;
  354.     message    : Str255;
  355. BEGIN
  356.     SetCursor(qd.arrow);
  357.     GetIndString(message, kErrStrings, error);
  358.     ParamText(message, '', '', '');
  359.     itemHit := Alert(rUserAlert, NIL);
  360. END; {AlertUser}
  361.  
  362.  
  363. {$S Main}
  364. PROCEDURE GetTERect(window: WindowPtr; VAR teRect: Rect);
  365.  
  366. {return a rectangle that is inset from the portRect by the size of
  367. the scrollbars and a little extra margin.}
  368.  
  369. BEGIN
  370.     teRect := window^.portRect;
  371.     InsetRect(teRect, kTextMargin, kTextMargin);            {adjust for margin}
  372.     teRect.bottom := teRect.bottom - kScrollbarAdjust;    {and for the scrollbars}
  373.     teRect.right := teRect.right - kScrollbarAdjust;
  374. END; {GetTERect}
  375.  
  376.  
  377. {$S Main}
  378. FUNCTION DoCloseWindow(window: WindowPtr) : BOOLEAN;
  379.  
  380. {Close a window. This handles desk accessory and application windows.}
  381.  
  382. {1.01 - At this point, if there was a document associated with a
  383.  window, you could do any document saving processing if it is 'dirty'.
  384.  DoCloseWindow would return TRUE if the window actually closed, i.e.,
  385.  the user didn’t cancel from a save dialog. This result is handy when
  386.  the user quits an application, but then cancels the save of a document
  387.  associated with a window.}
  388.  
  389. BEGIN
  390.     DoCloseWindow := TRUE;
  391.     IF IsDAWindow(window) THEN
  392.         CloseDeskAcc(WindowPeek(window)^.windowKind)
  393.     ELSE IF IsAppWindow(window) THEN BEGIN
  394.         WITH DocumentPeek(window)^ DO
  395.             IF docTE <> NIL THEN
  396.                 TEDispose(docTE);        {dispose the TEHandle}
  397.         {1.01 - We used to call DisposeWindow, but that was technically
  398.          incorrect, even though we allocated storage for the window on
  399.          the heap. We should instead call CloseWindow to have the structures
  400.          taken care of and then dispose of the storage ourselves.}
  401.         CloseWindow(window);
  402.         DisposePtr(Ptr(window));
  403.         gNumDocuments := gNumDocuments - 1;
  404.     END;
  405. END; {DoCloseWindow}
  406.  
  407.  
  408. {$S Main}
  409. PROCEDURE AdjustViewRect(docTE: TEHandle);
  410.  
  411. {Update the TERec's view rect so that it is the greatest multiple of
  412. the lineHeight and still fits in the old viewRect.}
  413.  
  414. BEGIN
  415.     WITH docTE^^ DO BEGIN
  416.         viewRect.bottom := (((viewRect.bottom - viewRect.top) DIV lineHeight) *
  417.                             lineHeight) + viewRect.top;
  418.     END;
  419. END; {AdjustViewRect}
  420.  
  421.  
  422. {$S Main}
  423. PROCEDURE AdjustTE(window: WindowPtr);
  424.  
  425. {Scroll the TERec around to match up to the potentially updated scrollbar
  426. values. This is really useful when the window resizes such that the
  427. scrollbars become inactive and the TERec had been previously scrolled.}
  428.  
  429. VAR
  430.     value    : INTEGER;
  431. BEGIN
  432.     WITH DocumentPeek(window)^ DO BEGIN
  433.         TEScroll((docTE^^.viewRect.left - docTE^^.destRect.left) - GetControlValue(docHScroll),
  434.                 (docTE^^.viewRect.top - docTE^^.destRect.top) -
  435.                     (GetControlValue(docVScroll) * docTE^^.lineHeight),
  436.                 docTE);
  437.     END;
  438. END; {AdjustTE}
  439.  
  440.  
  441. {$S Main}
  442. PROCEDURE AdjustHV(isVert: BOOLEAN; control: ControlHandle; docTE: TEHandle; canRedraw: BOOLEAN);
  443.  
  444. {Calculate the new control maximum value and current value, whether it is the horizontal or
  445. vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  446. vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  447. width to the width of the viewRect. The current values are set by comparing the offset between
  448. the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  449. calling ShowControl.}
  450.  
  451. VAR
  452.     value, lines, max    : INTEGER;
  453.     oldValue, oldMax    : INTEGER;
  454. BEGIN
  455.     oldValue := GetControlValue(control);
  456.     oldMax := GetControlMaximum(control);
  457.     IF isVert THEN BEGIN
  458.         lines := docTE^^.nLines;
  459.         {since nLines isn’t right if the last character is a return, check for that case}
  460.         IF Ptr(ORD(docTE^^.hText^) + docTE^^.teLength - 1)^ = kCRChar THEN
  461.             lines := lines + 1;
  462.         max := lines - ((docTE^^.viewRect.bottom - docTE^^.viewRect.top) DIV docTE^^.lineHeight);
  463.     END ELSE
  464.         max := kMaxDocWidth - (docTE^^.viewRect.right - docTE^^.viewRect.left);
  465.     IF max < 0 THEN max := 0;            {check for negative values}
  466.     SetControlMaximum(control, max);
  467.     IF isVert THEN
  468.         value := (docTE^^.viewRect.top - docTE^^.destRect.top) DIV docTE^^.lineHeight
  469.     ELSE
  470.         value := docTE^^.viewRect.left - docTE^^.destRect.left;
  471.     IF value < 0 THEN
  472.         value := 0
  473.     ELSE IF value > max THEN
  474.         value := max;                    {pin the value to within range}
  475.     SetControlValue(control, value);
  476.     IF canRedraw & ( (max <> oldMax) | (value <> oldValue) ) THEN
  477.         ShowControl(control);            {check to see if the control can be re-drawn}
  478. END; {AdjustHV}
  479.  
  480.  
  481. {$S Main}
  482. PROCEDURE AdjustScrollValues(window: WindowPtr; canRedraw: BOOLEAN);
  483.  
  484. {Simply call the common adjust routine for the vertical and horizontal scrollbars.}
  485.  
  486. BEGIN
  487.     WITH DocumentPeek(window)^ DO BEGIN
  488.         AdjustHV(TRUE, docVScroll, docTE, canRedraw);
  489.         AdjustHV(FALSE, docHScroll, docTE, canRedraw);
  490.     END;
  491. END; {AdjustScrollValues}
  492.  
  493.  
  494. {$S Main}
  495. PROCEDURE AdjustScrollSizes(window: WindowPtr);
  496.  
  497. {Re-calculate the position and size of the viewRect and the scrollbars.
  498.  kScrollTweek compensates for off-by-one requirements of the scrollbars
  499.  to have borders coincide with the growbox.}
  500.  
  501. VAR
  502.     teRect    : Rect;
  503. BEGIN
  504.     GetTERect(window, teRect);                                        {start with teRect}
  505.     WITH DocumentPeek(window)^, window^.portRect DO BEGIN
  506.         docTE^^.viewRect := teRect;
  507.         AdjustViewRect(docTE);                                        {snap to nearest line}
  508.         MoveControl(docVScroll, right - kScrollbarAdjust, -1);
  509.         SizeControl(docVScroll, kScrollbarWidth, (bottom - top) -
  510.                         (kScrollbarAdjust - kScrollTweek));
  511.         MoveControl(docHScroll, -1, bottom - kScrollbarAdjust);
  512.         SizeControl(docHScroll, (right - left) - (kScrollbarAdjust -
  513.                         kScrollTweek), kScrollbarWidth);
  514.     END;
  515. END; {AdjustScrollSizes}
  516.  
  517.  
  518. {$S Main}
  519. PROCEDURE AdjustScrollbars(window: WindowPtr; needsResize: BOOLEAN);
  520.  
  521. {Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  522. and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  523. then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  524. by jamming a $FF in their contrlVis fields.}
  525.  
  526. VAR
  527.     oldMax, oldVal    : INTEGER;
  528. BEGIN
  529.     WITH DocumentPeek(window)^ DO BEGIN
  530.         {First, turn visibility of scrollbars off so we won’t get unwanted redrawing}
  531.         docVScroll^^.contrlVis := kControlInvisible;    {turn them off}
  532.         docHScroll^^.contrlVis := kControlInvisible;
  533.         IF needsResize THEN                                {move and size if needed}
  534.             AdjustScrollSizes(window);
  535.         AdjustScrollValues(window, NOT needsResize);    {fool with max and current value}
  536.         {Now, restore visibility in case we never had to ShowControl during adjustment}
  537.         docVScroll^^.contrlVis := kControlVisible;        {turn them on}
  538.         docHScroll^^.contrlVis := kControlVisible;
  539.     END;
  540. END; {AdjustScrollbars}
  541.  
  542.  
  543. {$S Main}
  544. {$PUSH} {$Z+}
  545. PROCEDURE PascalClickLoop;
  546.  
  547. {Gets called from our assembly language routine, AsmClickLoop, which is in
  548.  turn called by the TEClick toolbox routine. Saves the windows clip region,
  549.  sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  550.  amount, then restores the clip region.}
  551.  
  552. VAR
  553.     window    : WindowPtr;
  554.     region    : RgnHandle;
  555. BEGIN
  556.     window := FrontWindow;
  557.     region := NewRgn;
  558.     GetClip(region);                    {save the old clip}
  559.     ClipRect(window^.portRect);            {set the new clip}
  560.     AdjustScrollValues(window, TRUE);    {pass TRUE for canRedraw}
  561.     SetClip(region);                    {restore the old clip}
  562.     DisposeRgn(region);
  563. END; {PascalClickLoop}
  564. {$POP}
  565.  
  566.  
  567. {$S Main}
  568. {$PUSH} {$Z+}
  569. FUNCTION GetOldClickLoop : TEClickLoopUPP;
  570.  
  571. {Gets called from our assembly language routine, AsmClickLoop, which is in
  572. turn called by the TEClick toolbox routine. It returns the address of the
  573. default clickLoop routine that was put into the TERec by TEAutoView to
  574. AsmClickLoop so that it can call it.}
  575.  
  576. BEGIN
  577.     GetOldClickLoop := DocumentPeek(FrontWindow)^.docClick;
  578. END; {GetOldClickLoop}
  579. {$POP}
  580.  
  581.  
  582. PROCEDURE AsmClickLoop; EXTERNAL;
  583.  
  584. {A reference to our assembly language routine that gets attached to the clickLoop
  585. field of our TE record.}
  586.  
  587.  
  588. {$S Main}
  589. PROCEDURE DoNew;
  590.  
  591. {Create a new document and window.}
  592.  
  593. VAR
  594.     good, ignore        : BOOLEAN;
  595.     storage                : Ptr;
  596.     window                : WindowPtr;
  597.     destRect, viewRect    : Rect;
  598.  
  599. BEGIN
  600.     storage := NewPtr(SIZEOF(DocumentRecord));
  601.     IF storage <> NIL THEN BEGIN
  602.         window := GetNewWindow(rDocWindow, storage, WindowPtr(-1));
  603.         IF window <> NIL THEN BEGIN
  604.             gNumDocuments := gNumDocuments + 1;    {this will be decremented when we call DoCloseWindow}
  605.             good := FALSE;
  606.             SetPort(window);
  607.             WITH window^, DocumentPeek(window)^ DO BEGIN
  608.                 GetTERect(window, viewRect);
  609.                 destRect := viewRect;
  610.                 destRect.right := destRect.left + kMaxDocWidth;
  611.                 docTE := TENew(destRect, viewRect);
  612.                 IF docTE <> NIL THEN BEGIN        {1.02 - moved}
  613.                     good := TRUE;                {if TENew succeeded, we have a good document}
  614.                     AdjustViewRect(docTE);
  615.                     TEAutoView(TRUE, docTE);
  616.                     docClick := docTE^^.clickLoop;
  617.                     docTE^^.clickLoop := @AsmClickLoop;
  618.                 END;
  619.                 IF good THEN BEGIN
  620.                     docVScroll := GetNewControl(rVScroll, window);
  621.                     good := (docVScroll <> NIL);
  622.                 END;
  623.                 IF good THEN BEGIN
  624.                     docHScroll := GetNewControl(rHScroll, window);
  625.                     good := (docHScroll <> NIL);
  626.                 END;
  627.                 IF good THEN BEGIN
  628.                     {FALSE to AdjustScrollValues means musn’t redraw; technically, of course,
  629.                     the window is hidden so it wouldn’t matter whether we called ShowControl or not.}
  630.                     AdjustScrollValues(window, FALSE);
  631.                     ShowWindow(window);            {if the document is good, make the window visible}
  632.                 END ELSE BEGIN
  633.                     ignore := DoCloseWindow(window);    {otherwise regret we ever created it...}
  634.                     AlertUser(eNoWindow);                {and tell user}
  635.                 END
  636.             END;
  637.         END ELSE
  638.             DisposePtr(storage);                    {get rid of the storage if it is never used}
  639.     END;
  640. END; {DoNew}
  641.  
  642.  
  643. {$S Main}
  644. PROCEDURE BigBadError(error: INTEGER);
  645. BEGIN
  646.     AlertUser(error);
  647.     ExitToShell;
  648. END;
  649.  
  650.  
  651. {$S Initialize}
  652. PROCEDURE Initialize;
  653.  
  654. {Set up the whole world, including global variables, Toolbox managers,
  655.  menus, and a single blank document.}
  656.  
  657. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  658.  this module. If an error is detected, instead of merely doing an ExitToShell,
  659.  which leaves the user without much to go on, we call AlertUser, which puts
  660.  up a simple alert that just says an error occurred and then calls ExitToShell.
  661.  Since there is no other cleanup needed at this point if an error is detected,
  662.  this form of error- handling is acceptable. If more sophisticated error recovery
  663.  is needed, an exception mechanism, such as is provided by Signals, can be used.}
  664.  
  665. VAR
  666.     menuBar                : Handle;
  667.     total, contig        : LongInt;
  668.     ignoreResult        : BOOLEAN;
  669.     event                : EventRecord;
  670.     count, ignoreError    : INTEGER;
  671.     
  672.     PROCEDURE BigBadError(error: INTEGER);
  673.     BEGIN
  674.         AlertUser(error);
  675.         ExitToShell;
  676.     END;
  677.  
  678. BEGIN
  679.     gInBackground := FALSE;
  680.  
  681.     InitGraf(@qd.thePort);
  682.     InitFonts;
  683.     InitWindows;
  684.     InitMenus;
  685.     TEInit;
  686.     InitDialogs(NIL);
  687.     InitCursor;
  688.  
  689.     {Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  690.      if you are using it.}
  691.     {NOTE -- It is no longer necessary, and actually unhealthy, to check
  692.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  693.      of checking for port availability themselves.}
  694.     
  695.     {This next bit of code is necessary to allow the default button of our
  696.      alert be outlined.
  697.      1.02 - Changed to call EventAvail so that we don't lose some important
  698.      events.}
  699.      
  700.     FOR count := 1 TO 3 DO
  701.         ignoreResult := EventAvail(everyEvent, event);
  702.     
  703.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  704.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  705.      call to SysEnvirons by calling it after initializing AppleTalk.}
  706.      
  707.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  708.     
  709.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  710.     
  711.     IF gMac.machineType < 0 THEN BigBadError(eWrongMachine);
  712.     
  713.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  714.      in TrapAvailable if a tool trap value is out of range.}
  715.      
  716.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  717.  
  718.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  719.      ApplicationZone, and StackSpace and comparing that to the minimum size we told
  720.      MultiFinder we needed. This did not work well because it assumed too much about
  721.      the relationship between what we asked MultiFinder for and what we would actually
  722.      get back, as well as how to measure it. Instead, we will use an alternate
  723.      method comprised of two steps.}
  724.      
  725.     {It is better to first check the size of the application heap against a value
  726.      that you have determined is the smallest heap the application can reasonably
  727.      work in. This number should be derived by examining the size of the heap that
  728.      is actually provided by MultiFinder when the minimum size requested is used.
  729.      The derivation of the minimum size requested from MultiFinder is described
  730.      in Sample.h. The check should be made because the preferred size can end up
  731.      being set smaller than the minimum size by the user. This extra check acts to
  732.      insure that your application is starting from a solid memory foundation.}
  733.      
  734.     IF ORD(GetApplLimit) - ORD(ApplicationZone) < kMinHeap THEN BigBadError(eSmallSize);
  735.     
  736.     {Next, make sure that enough memory is free for your application to run. It
  737.      is possible for a situation to arise where the heap may have been of required
  738.      size, but a large scrap was loaded which left too little memory. To check for
  739.      this, call PurgeSpace and compare the result with a value that you have determined
  740.      is the minimum amount of free memory your application needs at initialization.
  741.      This number can be derived several different ways. One way that is fairly
  742.      straightforward is to run the application in the minimum size configuration
  743.      as described previously. Call PurgeSpace at initialization and examine the value
  744.      returned. However, you should make sure that this result is not being modified
  745.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  746.      PurgeSpace. Make sure to remove that call before shipping, though.}
  747.      
  748.     {* ZeroScrap; *}
  749.     PurgeSpace(total, contig);
  750.     IF total < kMinSpace THEN
  751.         IF UnloadScrap <> noErr THEN
  752.             BigBadError(eNoMemory)
  753.         ELSE BEGIN
  754.             PurgeSpace(total, contig);
  755.             IF total < kMinSpace THEN
  756.                 BigBadError(eNoMemory);
  757.         END;
  758.  
  759.     {The extra benefit to waiting until after the Toolbox Managers have been initialized
  760.      to check memory is that we can now give the user an alert to tell her/him what
  761.      happened. Although it is possible that the memory situation could be worsened by
  762.      displaying an alert, MultiFinder would gracefully exit the application with
  763.      an informative alert if memory became critical. Here we are acting more
  764.      in a preventative manner to avoid future disaster from low-memory problems.}
  765.  
  766.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  767.     IF menuBar = NIL THEN
  768.         BigBadError(eNoMemory);
  769.     SetMenuBar(menuBar);                    {install menus}
  770.     DisposeHandle(menuBar);
  771.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  772.     DrawMenuBar;
  773.  
  774.     gNumDocuments := 0;
  775.  
  776.     {do other initialization here}
  777.  
  778.     DoNew;                                    {create a single empty document}
  779. END; {Initialize}
  780.  
  781.  
  782. (**************************************************************************************
  783. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  784.  
  785. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  786.  and not having to worry about updating the windows, but it suffered
  787.  from a fatal flaw. If a desk accessory owned two windows, it would
  788.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  789.  got around to calling DoCloseWindow for that other window that was already
  790.  closed, things would go very poorly. Another option would be to have a
  791.  procedure, GetRearWindow, that would go through the window list and return
  792.  the last window. Instead, we decided to present the standard approach
  793.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  794.  has a potential benefit in that the window whose document needs to be saved
  795.  may be visible since it is the front window, therefore decreasing the
  796.  chance of user confusion. For aesthetic reasons, the windows in the
  797.  application should be checked for updates periodically and have the
  798.  updates serviced.}
  799. **************************************************************************************)
  800.  
  801.  
  802. {$S Main}
  803. PROCEDURE Terminate;
  804.  
  805. {Clean up the application and exit. We close all of the windows so that
  806.  they can update their documents, if any.}
  807.  
  808. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  809.  shell, but will return instead.}
  810.  
  811. VAR
  812.     aWindow    : WindowPtr;
  813.     closed    : BOOLEAN;
  814.  
  815. BEGIN
  816.     closed := TRUE;
  817.     REPEAT
  818.         aWindow := FrontWindow;                    {get the current front window}
  819.         IF aWindow <> NIL THEN
  820.             closed := DoCloseWindow(aWindow);    {close this window}
  821.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  822.     IF closed THEN
  823.         ExitToShell;                            {exit if no cancellation}
  824. END; {Terminate}
  825.  
  826.  
  827. {$S Main}
  828. PROCEDURE AdjustMenus;
  829.  
  830. {Enable and disable menus based on the current state.
  831.  The user can only select enabled menu items. We set up all the menu items
  832.  before calling MenuSelect or MenuKey, since these are the only times that
  833.  a menu item can be selected. Note that MenuSelect is also the only time
  834.  the user will see menu items. This approach to deciding what enable/
  835.  disable state a menu item has the advantage of concentrating all the decision-
  836.  making in one routine, as opposed to being spread throughout the application.
  837.  Other application designs may take a different approach that may or may not be
  838.  as valid.}
  839.  
  840. VAR
  841.     window            : WindowPtr;
  842.     menu            : MenuHandle;
  843.     offset            : LONGINT;
  844.     undo            : BOOLEAN;
  845.     cutCopyClear    : BOOLEAN;
  846.     paste            : BOOLEAN;
  847.  
  848. BEGIN
  849.     window := FrontWindow;
  850.  
  851.     menu := GetMenuHandle(mFile);
  852.     IF gNumDocuments < kMaxOpenDocuments THEN
  853.         EnableItem(menu, iNew)        {New is enabled when we can open more documents}
  854.     ELSE
  855.         DisableItem(menu, iNew);
  856.     IF window <> NIL THEN            {Close is enabled when there is a window to close}
  857.         EnableItem(menu, iClose)
  858.     ELSE
  859.         DisableItem(menu, iClose);
  860.  
  861.     menu := GetMenuHandle(mEdit);
  862.     undo := FALSE;
  863.     cutCopyClear := FALSE;
  864.     paste := FALSE;
  865.     IF IsDAWindow(window) THEN BEGIN
  866.         undo := TRUE;                {all editing is enabled for DA windows}
  867.         cutCopyClear := TRUE;
  868.         paste := TRUE;
  869.     END ELSE IF IsAppWindow(window) THEN BEGIN
  870.         WITH DocumentPeek(window)^.docTE^^ DO
  871.             IF selStart < selEnd THEN
  872.                 cutCopyClear := TRUE;
  873.                 {Cut, Copy, and Clear is enabled for app. windows with selections}
  874.         IF GetScrap(NIL, 'TEXT', offset) > 0 THEN
  875.             paste := TRUE;            {Paste is enabled for app. windows}
  876.     END;
  877.     IF undo THEN
  878.         EnableItem(menu, iUndo)
  879.     ELSE
  880.         DisableItem(menu, iUndo);
  881.     IF cutCopyClear THEN BEGIN
  882.         EnableItem(menu, iCut);
  883.         EnableItem(menu, iCopy);
  884.         EnableItem(menu, iClear);
  885.     END ELSE BEGIN
  886.         DisableItem(menu, iCut);
  887.         DisableItem(menu, iCopy);
  888.         DisableItem(menu, iClear);
  889.     END;
  890.     IF paste THEN
  891.         EnableItem(menu, iPaste)
  892.     ELSE
  893.         DisableItem(menu, iPaste);
  894. END; {AdjustMenus}
  895.  
  896.  
  897. {$S Main}
  898. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  899.  
  900. {This is called when an item is chosen from the menu bar (after calling
  901.  MenuSelect or MenuKey). It does the right thing for each command.}
  902.  
  903. VAR
  904.     menuID, menuItem        : INTEGER;
  905.     itemHit, daRefNum        : INTEGER;
  906.     daName                    : Str255;
  907.     ignoreResult, saveErr    : OSErr;
  908.     handledByDA                : BOOLEAN;
  909.     te                        : TEHandle;
  910.     window                    : WindowPtr;
  911.     ignore                    : BOOLEAN;
  912.     aHandle                    : Handle;
  913.     oldSize, newSize        : LongInt;
  914.     total, contig            : LongInt;
  915.  
  916. BEGIN
  917.     window := FrontWindow;
  918.     menuID := HiWord(menuResult);    {use built-ins (for efficiency)...}
  919.     menuItem := LoWord(menuResult);    {to get menu item number and menu number}
  920.     CASE menuID OF
  921.     
  922.         mApple:
  923.             CASE menuItem OF
  924.                 iAbout:                {bring up alert for About}
  925.                     itemHit := Alert(rAboutAlert, NIL);
  926.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  927.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  928.                     daRefNum := OpenDeskAcc(daName);
  929.                 END;
  930.             END;
  931.             
  932.         mFile:
  933.             CASE menuItem OF
  934.                 iNew:
  935.                     DoNew;
  936.                 iClose:
  937.                     ignore := DoCloseWindow(window); {we don't care if cancelled}
  938.                 iQuit:
  939.                     Terminate;
  940.             END;
  941.             
  942.         mEdit: BEGIN                {call SystemEdit for DA editing & MultiFinder}
  943.             IF NOT SystemEdit(menuItem-1) THEN BEGIN
  944.                 te := DocumentPeek(window)^.docTE;
  945.                 CASE menuItem OF
  946.                 
  947.                     iCut: BEGIN        {after cutting, export the TE scrap}
  948.                         IF ZeroScrap = noErr THEN BEGIN
  949.                             PurgeSpace(total, contig);
  950.                             IF (te^^.selEnd - te^^.selStart) + kTESlop > contig THEN
  951.                                 AlertUser(eNoSpaceCut)
  952.                             ELSE BEGIN
  953.                                 TECut(te);
  954.                                 IF TEToScrap <> noErr THEN BEGIN
  955.                                     AlertUser(eNoCut);
  956.                                     ignoreResult := ZeroScrap;
  957.                                 END;
  958.                             END;
  959.                         END;
  960.                     END;
  961.                     
  962.                     iCopy: BEGIN    {after copying, export the TE scrap}
  963.                         IF ZeroScrap = noErr THEN BEGIN
  964.                             TECopy(te);
  965.                             IF TEToScrap <> noErr THEN BEGIN
  966.                                 AlertUser(eNoCopy);
  967.                                 ignoreResult := ZeroScrap;
  968.                             END;
  969.                         END;
  970.                     END;
  971.                     
  972.                     iPaste: BEGIN    {import the TE scrap before pasting}
  973.                         IF TEFromScrap = noErr THEN BEGIN
  974.                             IF TEGetScrapLength + (te^^.teLength -
  975.                                 (te^^.selEnd - te^^.selStart)) > kMaxTELength THEN
  976.                                 AlertUser(eExceedPaste)
  977.                             ELSE BEGIN
  978.                                     aHandle := Handle(TEGetText(te));
  979.                                     oldSize := GetHandleSize(aHandle);
  980.                                     newSize := oldSize + TEGetScrapLength + kTESlop;
  981.                                     SetHandleSize(aHandle, newSize);
  982.                                     saveErr := MemError;
  983.                                     SetHandleSize(aHandle, oldSize);
  984.                                     IF saveErr <> noErr THEN
  985.                                         AlertUser(eNoSpacePaste)
  986.                                     ELSE
  987.                                         TEPaste(te);
  988.                                 END;
  989.                         END ELSE
  990.                             AlertUser(eNoPaste);
  991.                     END;
  992.                     
  993.                     iClear:
  994.                         TEDelete(te);
  995.                         
  996.                 END;
  997.                 AdjustScrollbars(window, FALSE);
  998.                 AdjustTE(window);
  999.             END;
  1000.         END;
  1001.     END;
  1002.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  1003. END; {DoMenuCommand}
  1004.  
  1005.  
  1006. {$S Main}
  1007. PROCEDURE DrawWindow(window: WindowPtr);
  1008.  
  1009. {Draw the contents of an application window.}
  1010.  
  1011. BEGIN
  1012.     SetPort(window);
  1013.     WITH window^ DO BEGIN
  1014.         EraseRect(portRect);        {as per TextEdit chapter of Inside Macintosh}
  1015.         DrawControls(window);        {this ordering makes for a better appearance}
  1016.         DrawGrowIcon(window);
  1017.         TEUpdate(portRect, DocumentPeek(window)^.docTE);
  1018.     END;
  1019. END; {DrawWindow}
  1020.  
  1021.  
  1022. {$S Main}
  1023. FUNCTION GetSleep: LONGINT;
  1024.  
  1025. {Calculate a sleep value for WaitNextEvent. This takes into account the things
  1026.  that DoIdle does with idle time.}
  1027.  
  1028. VAR
  1029.     sleep    : LONGINT;
  1030.     window    : WindowPtr;
  1031.  
  1032. BEGIN
  1033.     sleep := MAXLONGINT;                    {default value for sleep}
  1034.     IF NOT gInBackground THEN BEGIN            {if we are in front...}
  1035.         window := FrontWindow;            {and the front window is ours...}
  1036.         IF IsAppWindow(window) THEN BEGIN
  1037.             WITH DocumentPeek(window)^.docTE^^ DO
  1038.                 IF selStart = selEnd THEN    {and the selection is an insertion point...}
  1039.                     sleep := GetCaretTime;    {we need to blink the insertion point}
  1040.         END;
  1041.     END;
  1042.     GetSleep := sleep;
  1043. END; {GetSleep}
  1044.  
  1045.  
  1046. {$S Main}
  1047. PROCEDURE CommonAction(control: ControlHandle; VAR amount: INTEGER);
  1048.  
  1049. {Common algorithm for setting the new value of a control. It returns the actual amount
  1050. the value of the control changed. Note the pinning is done for the sake of returning
  1051. the amount the control value changed.}
  1052.  
  1053. VAR
  1054.     value, max    : INTEGER;
  1055.     window        : WindowPtr;
  1056. BEGIN
  1057.     value := GetControlValue(control);    {get current value}
  1058.     max := GetControlMaximum(control);        {and max value}
  1059.     amount := value - amount;
  1060.     IF amount < 0 THEN
  1061.         amount := 0
  1062.     ELSE IF amount > max THEN
  1063.         amount := max;
  1064.     SetControlValue(control, amount);
  1065.     amount := value - amount;        {calculate true change}
  1066. END; {CommonAction}
  1067.  
  1068.  
  1069. {$S Main}
  1070. PROCEDURE VActionProc(control: ControlHandle; part: INTEGER);
  1071.  
  1072. {Determines how much to change the value of the vertical scrollbar by and how
  1073. much to scroll the TE record.}
  1074.  
  1075. VAR
  1076.     amount    : INTEGER;
  1077.     window    : WindowPtr;
  1078. BEGIN
  1079.     IF part <> 0 THEN BEGIN
  1080.         window := control^^.contrlOwner;
  1081.         WITH DocumentPeek(window)^, DocumentPeek(window)^.docTE^^ DO BEGIN
  1082.             CASE part OF
  1083.                 inUpButton, inDownButton:
  1084.                     amount := 1;                                                {one line}
  1085.                 inPageUp, inPageDown:
  1086.                     amount := (viewRect.bottom - viewRect.top) DIV lineHeight;    {one page}
  1087.             END;
  1088.             IF (part = inDownButton) | (part = inPageDown) THEN
  1089.                 amount := -amount;                                                {reverse direction}
  1090.             CommonAction(control, amount);
  1091.             IF amount <> 0 THEN
  1092.                 TEScroll(0, amount * docTE^^.lineHeight, docTE);
  1093.         END;
  1094.     END;
  1095. END; {VActionProc}
  1096.  
  1097.  
  1098. {$S Main}
  1099. PROCEDURE HActionProc(control: ControlHandle; part: INTEGER);
  1100.  
  1101. {Determines how much to change the value of the horizontal scrollbar by and how
  1102. much to scroll the TE record.}
  1103.  
  1104. VAR
  1105.     amount    : INTEGER;
  1106.     window    : WindowPtr;
  1107. BEGIN
  1108.     IF part <> 0 THEN BEGIN
  1109.         window := control^^.contrlOwner;
  1110.         WITH DocumentPeek(window)^, DocumentPeek(window)^.docTE^^ DO BEGIN
  1111.             CASE part OF
  1112.                 inUpButton, inDownButton:                                        {a few pixels}
  1113.                     amount := kButtonScroll;
  1114.                 inPageUp, inPageDown:
  1115.                     amount := viewRect.right - viewRect.left;                    {a page}
  1116.             END;
  1117.             IF (part = inDownButton) | (part = inPageDown) THEN
  1118.                 amount := -amount;                                                {reverse direction}
  1119.             CommonAction(control, amount);
  1120.             IF amount <> 0 THEN
  1121.                 TEScroll(amount, 0, docTE);
  1122.         END;
  1123.     END;
  1124. END; {HActionProc}
  1125.  
  1126.  
  1127. {$S Main}
  1128. PROCEDURE DoIdle;
  1129.  
  1130. {This is called whenever we get an null event or a mouse-moved event.
  1131.  It takes care of necessary periodic actions. For this program, it calls TEIdle.}
  1132.  
  1133. VAR
  1134.     window    : WindowPtr;
  1135.  
  1136. BEGIN
  1137.     window := FrontWindow;
  1138.     IF IsAppWindow(window) THEN
  1139.         TEIdle(DocumentPeek(window)^.docTE);
  1140. END; {DoIdle}
  1141.  
  1142.  
  1143. {$S Main}
  1144. PROCEDURE DoKeyDown(event: EventRecord);
  1145.  
  1146. {This is called for any keyDown or autoKey events, except when the
  1147.  Command key is held down. It looks at the frontmost window to decide what
  1148.  to do with the key typed.}
  1149.  
  1150. VAR
  1151.     window    : WindowPtr;
  1152.     key        : CHAR;
  1153.     te        : TEHandle;
  1154.  
  1155. BEGIN
  1156.     window := FrontWindow;
  1157.     IF IsAppWindow(window) THEN BEGIN
  1158.         te := DocumentPeek(window)^.docTE;
  1159.         key := CHR(BAnd(event.message, charCodeMask));
  1160.         IF (key = CHR(kDelChar)) |                            {don't count deletes}
  1161.             (te^^.teLength - (te^^.selEnd - te^^.selStart)
  1162.                             + 1 < kMaxTELength) THEN BEGIN    {but check haven't gone past}
  1163.             TEKey(key, te);
  1164.             AdjustScrollbars(window, FALSE);
  1165.             AdjustTE(window);
  1166.         END ELSE
  1167.             AlertUser(eExceedChar);
  1168.     END;
  1169. END; {DoKeyDown}
  1170.  
  1171.  
  1172. {$S Main}
  1173. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  1174.  
  1175. {Called when a mouseDown occurs in the content of a window.}
  1176.  
  1177. VAR
  1178.     mouse        : Point;
  1179.     control        : ControlHandle;
  1180.     part, value    : INTEGER;
  1181.     shiftDown    : BOOLEAN;
  1182.     teRect        : Rect;
  1183.     upp            : ControlActionUPP;
  1184.     
  1185. BEGIN
  1186.     IF IsAppWindow(window) THEN BEGIN
  1187.         SetPort(window);
  1188.         mouse := event.where;                                            {get the click position}
  1189.         GlobalToLocal(mouse);                                            {convert to local coordinates}
  1190.         {see if we are in the viewRect. if so, we won’t check the controls}
  1191.         GetTERect(window, teRect);
  1192.         IF PtInRect(mouse, teRect) THEN BEGIN
  1193.             shiftDown := BAnd(event.modifiers, shiftKey) <> 0;    {extend if Shift is down}
  1194.             TEClick(mouse, shiftDown, DocumentPeek(window)^.docTE);
  1195.         END ELSE BEGIN
  1196.             part := FindControl(mouse, window, control);
  1197.             WITH DocumentPeek(window)^ DO
  1198.                 CASE part OF
  1199.                     0:;                                            {do nothing for viewRect case}
  1200.                     inThumb: BEGIN
  1201.                         value := GetControlValue(control);
  1202.                         part := TrackControl(control, mouse, NIL);
  1203.                         IF part <> 0 THEN BEGIN
  1204.                             value := value - GetControlValue(control);
  1205.                             IF value <> 0 THEN
  1206.                                 IF control = docVScroll THEN
  1207.                                     TEScroll(0, value * docTE^^.lineHeight, docTE)
  1208.                                 ELSE
  1209.                                     TEScroll(value, 0, docTE);
  1210.                         END;
  1211.                     END;
  1212.                     OTHERWISE BEGIN                                 {must be page or button}
  1213.                         IF control = docVScroll THEN
  1214.                             BEGIN
  1215.                             upp := NewControlActionProc(@VActionProc);
  1216.                             END
  1217.                         ELSE
  1218.                             BEGIN
  1219.                             upp := NewControlActionProc(@HActionProc);
  1220.                             END;
  1221.                         value := TrackControl(control, mouse, upp);
  1222.                         DisposeRoutineDescriptor(upp);
  1223.                     END;
  1224.                 END;
  1225.         END;
  1226.     END;
  1227. END; {DoContentClick}
  1228.  
  1229.  
  1230. {$S Main}
  1231. PROCEDURE ResizeWindow(window: WindowPtr);
  1232.  
  1233. {Called when the window has been resized to fix up the controls and content}
  1234.  
  1235. BEGIN
  1236.     WITH window^ DO BEGIN
  1237.         AdjustScrollbars(window, TRUE);
  1238.         AdjustTE(window);
  1239.         InvalRect(portRect);
  1240.     END;
  1241. END; {ResizeWindow}
  1242.  
  1243.  
  1244. {$S Main}
  1245. PROCEDURE GetLocalUpdateRgn(window: WindowPtr; localRgn: RgnHandle);
  1246.  
  1247. {Returns the update region in local coordinates}
  1248.  
  1249. BEGIN
  1250.     CopyRgn(WindowPeek(window)^.updateRgn, localRgn);                        {save old update region}
  1251.     WITH window^.portBits.bounds DO
  1252.         OffsetRgn(localRgn, left, top);                                        {convert to local coords}
  1253. END; {GetLocalUpdateRgn}
  1254.  
  1255.  
  1256. {$S Main}
  1257. PROCEDURE DoGrowWindow(window: WindowPtr; event: EventRecord);
  1258.  
  1259. {Called when a mouseDown occurs in the grow box of an active window. In
  1260.  order to eliminate any 'flicker', we want to invalidate only what is
  1261.  necessary. Since ResizeWindow invalidates the whole portRect, we save
  1262.  the old TE viewRect, intersect it with the new TE viewRect, and
  1263.  remove the result from the update region. However, we must make sure
  1264.  that any old update region that might have been around gets put back.}
  1265.  
  1266. VAR
  1267.     growResult        : LONGINT;
  1268.     tempRect        : Rect;
  1269.     tempRgn            : RgnHandle;
  1270.     ignoreResult    : BOOLEAN;
  1271.  
  1272. BEGIN
  1273.     WITH qd.screenBits.bounds DO
  1274.         SetRect(tempRect, kMinDocDim, kMinDocDim, right, bottom);            {set up limiting values}
  1275.     growResult := GrowWindow(window, event.where, tempRect);
  1276.     IF growResult <> 0 THEN                                                 {see if changed size}
  1277.         WITH DocumentPeek(window)^, window^ DO BEGIN
  1278.             tempRect := docTE^^.viewRect;                                    {save old text box}
  1279.             tempRgn := NewRgn;
  1280.             GetLocalUpdateRgn(window, tempRgn);                                {get localized update region}
  1281.             SizeWindow(window, LoWord(growResult), HiWord(growResult), TRUE);
  1282.             ResizeWindow(window);
  1283.             ignoreResult := SectRect(tempRect, docTE^^.viewRect, tempRect);    {find what stayed same}
  1284.             ValidRect(tempRect);                                            {take it out of update}
  1285.             InvalRgn(tempRgn);                                                {put back any prior update}
  1286.             DisposeRgn(tempRgn);
  1287.         END;
  1288. END; {DoGrowWindow}
  1289.  
  1290.  
  1291. {$S Main}
  1292. PROCEDURE DoZoomWindow(window: WindowPtr; part: INTEGER);
  1293.  
  1294. {Called when a mouseClick occurs in the zoom box of an active window.
  1295.  Everything has to get re-drawn here, so we don't mind that
  1296.  ResizeWindow invalidates the whole portRect.}
  1297.  
  1298. BEGIN
  1299.     WITH window^ DO BEGIN
  1300.         EraseRect(portRect);
  1301.         ZoomWindow(window, part, (window = FrontWindow));
  1302.         ResizeWindow(window);
  1303.     END;
  1304. END; {DoZoomWindow}
  1305.  
  1306.  
  1307. {$S Main}
  1308. PROCEDURE DoUpdate(window: WindowPtr);
  1309.  
  1310. {This is called when an update event is received for a window.
  1311.  It calls DrawWindow to draw the contents of an application window,
  1312.  but only if the visRgn is non-empty; for efficiency reasons,
  1313.  not because it is required.}
  1314.  
  1315. BEGIN
  1316.     IF IsAppWindow(window) THEN BEGIN
  1317.         BeginUpdate(window);                    {this sets up the visRgn}
  1318.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  1319.             DrawWindow(window);
  1320.         EndUpdate(window);
  1321.     END;
  1322. END; {DoUpdate}
  1323.  
  1324.  
  1325. {$S Main}
  1326. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  1327.  
  1328. {This is called when a window is activated or deactivated.}
  1329.  
  1330. VAR
  1331.     tempRgn, clipRgn    : RgnHandle;
  1332.     growRect            : Rect;
  1333.  
  1334. BEGIN
  1335.     IF IsAppWindow(window) THEN
  1336.         WITH DocumentPeek(window)^ DO
  1337.             IF becomingActive THEN BEGIN
  1338.                 {since we don’t want TEActivate to draw a selection in an area where
  1339.                  we’re going to erase and redraw, we’ll clip out the update region
  1340.                  before calling it.}
  1341.                 tempRgn := NewRgn;
  1342.                 clipRgn := NewRgn;
  1343.                 GetLocalUpdateRgn(window, tempRgn);            {get localized update region}
  1344.                 GetClip(clipRgn);
  1345.                 DiffRgn(clipRgn, tempRgn, tempRgn);            {subtract updateRgn from clipRgn}
  1346.                 SetClip(tempRgn);
  1347.                 TEActivate(docTE);                            {let TE do its thing}
  1348.                 SetClip(clipRgn);                            {restore the full-blown clipRgn}
  1349.                 DisposeRgn(tempRgn);
  1350.                 DisposeRgn(clipRgn);
  1351.  
  1352.                 {the controls need to be redrawn on activation:}
  1353.                 docVScroll^^.contrlVis := kControlVisible;
  1354.                 docHScroll^^.contrlVis := kControlVisible;
  1355.                 InvalRect(docVScroll^^.contrlRect);
  1356.                 InvalRect(docHScroll^^.contrlRect);
  1357.                 {the growbox needs to be redrawn on activation:}
  1358.                 growRect := window^.portRect;
  1359.                 WITH growRect DO BEGIN
  1360.                     top := bottom - kScrollbarAdjust;        {adjust for the scrollbars}
  1361.                     left := right - kScrollbarAdjust;
  1362.                     END;
  1363.                 InvalRect(growRect);
  1364.             END ELSE BEGIN
  1365.                 TEDeactivate(docTE);
  1366.                 {the controls should be hidden immediately on deactivation:}
  1367.                 HideControl(docVScroll);
  1368.                 HideControl(docHScroll);
  1369.                 {the growbox should be changed immediately on deactivation:}
  1370.                 DrawGrowIcon(window);
  1371.             END;
  1372. END; {DoActivate}
  1373.  
  1374.  
  1375. {$S Main}
  1376. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  1377.  
  1378. {Get the global coordinates of the mouse. When you call OSEventAvail
  1379.  it will return either a pending event or a null event. In either case,
  1380.  the where field of the event record will contain the current position
  1381.  of the mouse in global coordinates and the modifiers field will reflect
  1382.  the current state of the modifiers. Another way to get the global
  1383.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  1384.  being sure that thePort is set to a valid port.}
  1385.  
  1386. VAR
  1387.     event    : EventRecord;
  1388.     
  1389. BEGIN
  1390.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  1391.     mouse := event.where;                    {just the mouse position}
  1392. END;
  1393.  
  1394.  
  1395. {$S Main}
  1396. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  1397.  
  1398. {Change the cursor's shape, depending on its position. This also calculates the region
  1399.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  1400.  that region, an event is generated, causing this routine to be called. This
  1401.  allows us to change the region to the region the mouse is currently in. If
  1402.  there is more to the event than just “the mouse moved”, we get called before the
  1403.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  1404.  this is called again before we fall back into WNE.}
  1405.  
  1406.  
  1407. VAR
  1408.     window        : WindowPtr;
  1409.     arrowRgn    : RgnHandle;
  1410.     iBeamRgn    : RgnHandle;
  1411.     iBeamRect    : Rect;
  1412.  
  1413. BEGIN
  1414.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  1415.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  1416.         {calculate regions for different cursor shapes}
  1417.         arrowRgn := NewRgn;
  1418.         iBeamRgn := NewRgn;
  1419.  
  1420.         {start with a big, big rectangular region}
  1421.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  1422.  
  1423.         {calculate iBeamRgn}
  1424.         IF IsAppWindow(window) THEN BEGIN
  1425.             iBeamRect := DocumentPeek(window)^.docTE^^.viewRect;
  1426.             SetPort(window);                    {make a global version of the viewRect}
  1427.             WITH iBeamRect DO BEGIN
  1428.                 LocalToGlobal(topLeft);
  1429.                 LocalToGlobal(botRight);
  1430.             END;
  1431.             RectRgn(iBeamRgn, iBeamRect);
  1432.             WITH window^.portBits.bounds DO
  1433.                 SetOrigin(-left, -top);
  1434.             SectRgn(iBeamRgn, window^.visRgn, iBeamRgn);
  1435.             SetOrigin(0, 0);
  1436.         END;
  1437.  
  1438.         {subtract other regions from arrowRgn}
  1439.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  1440.         
  1441.         {change the cursor and the region parameter}
  1442.         IF PtInRgn(mouse, iBeamRgn) THEN BEGIN
  1443.             SetCursor(GetCursor(iBeamCursor)^^);
  1444.             CopyRgn(iBeamRgn, region);
  1445.         END ELSE BEGIN
  1446.             SetCursor(qd.arrow);
  1447.             CopyRgn(arrowRgn, region);
  1448.         END;
  1449.  
  1450.         {get rid of our local regions}
  1451.         DisposeRgn(arrowRgn);
  1452.         DisposeRgn(iBeamRgn);
  1453.     END;
  1454. END; {AdjustCursor}
  1455.  
  1456.  
  1457. {$S Main}
  1458. PROCEDURE DoEvent(event: EventRecord);
  1459.  
  1460. {Do the right thing for an event. Determine what kind of event it is, and call
  1461.  the appropriate routines.}
  1462.  
  1463. VAR
  1464.     part, err    : INTEGER;
  1465.     window        : WindowPtr;
  1466.     key            : CHAR;
  1467.     ignore        : BOOLEAN;
  1468.     aPoint        : Point;
  1469.  
  1470. BEGIN
  1471.     CASE event.what OF
  1472.         nullEvent:
  1473.             DoIdle;
  1474.         mouseDown: BEGIN
  1475.             part := FindWindow(event.where, window);
  1476.             CASE part OF
  1477.                 inMenuBar: BEGIN
  1478.                     AdjustMenus;
  1479.                     DoMenuCommand(MenuSelect(event.where));
  1480.                 END;
  1481.                 inSysWindow:
  1482.                     SystemClick(event, window);
  1483.                 inContent:
  1484.                     IF window <> FrontWindow THEN BEGIN
  1485.                         SelectWindow(window);
  1486.                         {DoEvent(event);}    {use this line for "do first click"}
  1487.                     END ELSE
  1488.                         DoContentClick(window, event);
  1489.                 inDrag:
  1490.                     DragWindow(window, event.where, qd.screenBits.bounds);
  1491.                 inGrow:
  1492.                     DoGrowWindow(window, event);
  1493.                 inGoAway:
  1494.                     IF TrackGoAway(window, event.where) THEN
  1495.                         ignore := DoCloseWindow(window);        {we don't care if cancelled}
  1496.                 inZoomIn, inZoomOut:
  1497.                     IF TrackBox(window, event.where, part) THEN
  1498.                         DoZoomWindow(window, part);
  1499.             END;
  1500.         END;
  1501.         keyDown, autoKey: BEGIN
  1502.             key := CHR(BAnd(event.message, charCodeMask));
  1503.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN BEGIN    {Command key down}
  1504.                 IF event.what = keyDown THEN BEGIN
  1505.                     AdjustMenus;            {enable/disable/check menu items properly}
  1506.                     DoMenuCommand(MenuKey(key));
  1507.                 END;
  1508.             END ELSE
  1509.                 DoKeyDown(event);
  1510.         END;                                {call DoActivate with the window and...}
  1511.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  1512.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  1513.         updateEvt:                            {call DoUpdate with the window to update}
  1514.             DoUpdate(WindowPtr(event.message));
  1515.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  1516.          to a diskEvt, so that the user can format a floppy.}
  1517.         diskEvt:
  1518.             IF HiWord(event.message) <> noErr THEN BEGIN
  1519.                 SetPt(aPoint, kDILeft, kDITop);
  1520.                 err := DIBadMount(aPoint, event.message);
  1521.             END;
  1522.         kOSEvent:
  1523.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  1524.                 kMouseMovedMessage:
  1525.                     DoIdle;                    {mouse moved is also an idle event}
  1526.                 kSuspendResumeMessage: BEGIN
  1527.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  1528.                     DoActivate(FrontWindow, NOT gInBackground);
  1529.                 END;
  1530.             END;
  1531.     END;
  1532. END; {DoEvent}
  1533.  
  1534.  
  1535. {$S Main}
  1536. PROCEDURE EventLoop;
  1537.  
  1538. {Get events forever, and handle them by calling DoEvent.
  1539.  Also call AdjustCursor each time through the loop.}
  1540.  
  1541. VAR
  1542.     cursorRgn    : RgnHandle;
  1543.     gotEvent    : BOOLEAN;
  1544.     event        : EventRecord;
  1545.     mouse        : Point;
  1546.  
  1547. BEGIN
  1548.     cursorRgn := NewRgn;        {we'll pass an empty region to WNE the first time thru}
  1549.     REPEAT
  1550.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  1551.             GetGlobalMouse(mouse);        {since we might go to sleep}
  1552.             AdjustCursor(mouse, cursorRgn);
  1553.             gotEvent := WaitNextEvent(everyEvent, event, GetSleep, cursorRgn);
  1554.         END ELSE BEGIN
  1555.             SystemTask;                    {must be called if using GetNextEvent}
  1556.             gotEvent := GetNextEvent(everyEvent, event);
  1557.         END;
  1558.         IF gotEvent THEN BEGIN
  1559.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  1560.             DoEvent(event);                {Handle the event only if for us.}
  1561.             END
  1562.         ELSE
  1563.             DoIdle;
  1564.         {If you are using modeless dialogs that have editText items,
  1565.          you will want to call IsDialogEvent to give the caret a chance
  1566.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  1567.          for a non-NIL value before calling IsDialogEvent.}
  1568.     UNTIL FALSE;    {loop forever}
  1569. END; {EventLoop}
  1570.  
  1571.  
  1572. PROCEDURE _DataInit; EXTERNAL;
  1573.  
  1574. {This routine is automatically linked in by the MPW Linker. This external
  1575.  reference to it is done so that we can unload its segment, %A5Init.}
  1576.  
  1577.  
  1578. {$S Main}
  1579. BEGIN
  1580.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  1581.     
  1582.     {1.01 - call to ForceEnvirons removed}
  1583.     {If you have stack requirements that differ from the default,
  1584.      then you could use SetApplLimit to increase StackSpace at 
  1585.      this point, before calling MaxApplZone.}
  1586.      
  1587.     MaxApplZone;            {expand the heap so code segments load at the top}
  1588.  
  1589.     Initialize;                {initialize the program}
  1590.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  1591.  
  1592.     EventLoop;                {call the main event loop}
  1593. END.
  1594.